from flask import request, jsonify, Blueprint
import json

from models import Composer
from config import static_prefix

bp = Blueprint('composer', __name__, url_prefix='/composer')


@bp.route('/all', methods=['GET'])
def composer_all():
    res = []
    composers = Composer.query.all()
    for i in composers:
        res.append({
            "composer_name": i.cps_name,
            "composer_name_e": i.cps_name_e,
            "pic_src": static_prefix + 'picture?type=composer&filename=' + i.pic_src,
            "intro": i.intro
        })
    return jsonify(res)


@bp.route('/detail', methods=['POST'])
def composer_detail():
    data = request.get_json()
    res = {'msg': '操作成功'}
    if 'cps_name' not in data:
        res['msg'] = '请求参数出错'
        return jsonify(res)
    composer = Composer.query.filter_by(cps_name=data['cps_name']).all()
    if len(composer) == 0:
        res['msg'] = '请求的歌剧不存在'
        return jsonify(res)
    composer = composer[0]
    res['cps_name'] = composer.cps_name
    res['cps_name_e'] = composer.cps_name_e
    res['pic_src'] = static_prefix + 'picture?type=composer&filename=' + composer.pic_src
    res['nation'] = composer.nation
    res['simple_intro'] = composer.intro
    res['exp_list'] = json.loads(composer.exp_list)
    res['piece_list'] = []
    # 构造 piece_list
    opr_list = composer.operas
    for opr in opr_list:
        res['piece_list'].append({
            'opr_name': opr.opr_name,
            'opr_pic_src': static_prefix + 'picture?type=opera&filename=' + opr.pic_src,
            'opr_name_e': opr.opr_name_e
        })
    print(res)
    return jsonify(res)
